'use strict';

describe('service', function() {
	beforeEach(module('PP.services'));

	describe('version', function() {
		it('should return current version', inject(function(version) {
			expect(version).toEqual('0.1');
		}));
	});

	describe('News service', function() {
		var newsService = null;
		var $timeout = null;

		beforeEach(inject(function(_newsService_, _$timeout_) {
			newsService = _newsService_;
			$timeout = _$timeout_;
		}));

		it('should be defined', function() {
			expect(newsService).toBeDefined();
		});

		describe('News service fail mechanism', function() {
			it('shuold define a fail rate', function() {
				expect(newsService.getFailRate()).toBeDefined();
			});

			it('should not fail when requested', function() {
				newsService.doNotFail();
				expect(newsService.getFailRate()).toBe(0);
			});

			it('should fail when requested', function() {
				var failCalled = false;
				newsService.nextRequestWillFail();

				newsService.getNews().then(function success(news) {
					throw 'Should have failed';
				}, function fail(reason) {
					failCalled = true;
					expect(reason).toBeDefined();
				});
				$timeout.flush();

				expect(failCalled).toBe(true);
			});

			it('should fail and then restore previous fail rate', function() {
				newsService.doNotFail();
				var previousFailRate = newsService.getFailRate();

				newsService.nextRequestWillFail();
				expect(newsService.getFailRate()).toBe(1);

				newsService.getNews().then(function() {
				});

				$timeout.flush();

				expect(newsService.getFailRate()).toBe(previousFailRate);
			});

		});

		describe('News service deterministic (no fail)', function() {
			beforeEach(function() {
				newsService.doNotFail();
			});

			it('should return asynchronously 2 news', function() {
				newsService.getNews().then(function(news) {
					expect(news.length).toEqual(2);
				});
				$timeout.flush();
			});

		});

	});
});
